<template>
  <div>
    <van-nav-bar title="附近电站" fixed />
    <div class="container" id="container"></div>
  </div>
</template>

<script>
const AMap = window.AMap
export default {
  name: 'Map',
  data () {
    return {
      list: [],
      center: [113.687238, 34.758278]
    }
  },
  methods: {
    initMap () {
      const map = new AMap.Map('container', {
        center: this.center,
        zoom: 10
      })
      this.map = map
    },
    initPosition () {
      const _this = this
      AMap.plugin('AMap.Geolocation', function () {
        var geolocation = new AMap.Geolocation({
          // 是否使用高精度定位，默认：true
          enableHighAccuracy: true,
          // 设置定位超时时间，默认：无穷大
          timeout: 10000,
          // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
          buttonOffset: new AMap.Pixel(10, 20),
          //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
          zoomToAccuracy: true,
          //  定位按钮的排放位置,  RB表示右下
          buttonPosition: 'RB'
        })

        geolocation.getCurrentPosition(function (status, result) {
          if (status === 'complete') {
            onComplete(result)
          } else {
            onError(result)
          }
        })

        function onComplete (data) {
          console.log(data)
        }

        function onError (data) {
          AMap.plugin('AMap.CitySearch', function () {
            const citySearch = new AMap.CitySearch()
            citySearch.getLocalCity(function (status, result) {
              if (status === 'complete' && result.info === 'OK') {
                // 查询成功，result即为当前所在城市信息
                const center = result.bounds.getCenter()
                if (_this.map) {
                  _this.map.setCenter(center)
                }
                _this.center = [center.lng, center.lat]
              } else {
                _this.$toast.success('定位失败！')
              }
            })
          })
        }
      })
    },
    initData () {
      this.$http.get('/restful/kxArea/getPage', {
        params: {
          page: 1,
          limit: 30
        }
      }).then(res => {
        if (res.code === 'ok') {
          this.list = res.data.records
          console.log(this.list)
        }
      })
    }
  },
  mounted () {
    this.initMap()
    this.initPosition()
    this.initData()
  }
}
</script>

<style scoped lang='less'>
.container {
  position: absolute; left: 0; top: 0;
  width: 100%;
  height: calc(100vh - 40px);
}
</style>

<style lang="less">
.amap-copyright, .amap-logo {
  z-index: -1;
}
</style>
